/**
 * get base64 from img Object
 * @param {img} img
 * @returns {String} base64
 */
function getBase64Image(img: any) {
  let canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  let ctx = canvas.getContext('2d')
  ctx?.drawImage(img, 0, 0, img.width, img.height)
  let dataURL = canvas.toDataURL('image/png')
  return dataURL
}

/**
 * 节流
 * @param {Function} fn -需要执行的函数
 * @param {Number} interval -节流时间
 */
function throttle(fn: { apply: (arg0: any, arg1: any[]) => void }, interval: number = 500) {
  let flag = true
  return function (this: any, ...args: any) {
    if (flag) {
      fn.apply(this, args)
      flag = false
      setTimeout(() => {
        flag = true
      }, interval)
    }
  }
}

/**
 * 防抖
 * @param {Function} fn -需要执行的函数
 * @param {Number} delay -时间
 */
function debounce(fn: { apply: (arg0: any, arg1: any) => void }, delay: number = 500) {
  let timeId: any = null
  return function (this: any, ...args: any) {
    if (timeId) {
      clearTimeout(timeId)
    }
    timeId = setTimeout(() => {
      timeId = null
      fn.apply(this, args)
    }, delay)
  }
}

export { getBase64Image, throttle, debounce }
